package 四数之和;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 四数之和     *************35行和40 的条件是关注点
 * @date 2022/10/23 11:24
 */
public class Demo18 {
    public static void main(String[] args) {
        int[] nums={2,2,2,2,2};
        List<List<Integer>> lists = fourSum(nums, 8);
        System.out.println(lists);
    }
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res=new ArrayList<>();
        //先排序
        Arrays.sort(nums);
        //开始遍历
        for (int i = 0; i < nums.length-1; i++) {
            //裁剪
            if(target>0&&nums[i]>target){
                return res;
            }
            //裁剪
            if (i>0&&nums[i]==nums[i-1]){
                continue;
            }
            for (int j = i+1; j < nums.length ; j++) {
                if(target>0&&(nums[i]+nums[j])>target){
                    //这里不是返回，而是结束j的循环循环
                    break;
                }

                //这里裁剪需要注意条件
                if (j>i+1&&nums[j]==nums[j-1]){
                    continue;
                }
                int left=j+1;
                int right= nums.length-1;
                while (left<right){
                    long sum=(long)nums[i]+(long)nums[j]+(long)nums[left]+(long)nums[right];
                    if(sum>target){
                        right--;
                    }else if(sum<target){
                        left++;
                    }else {
                        res.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
                        while (left<right&&nums[left]==nums[left+1]){
                            left++;
                        }
                        while (left<right&&nums[right]==nums[right-1]){
                            right--;
                        }
                        left++;
                        right--;
                    }
                }
            }

        }
        return res;
    }
}
